<template>
	<view class="layout" v-if="currentInfo">
		<swiper circular :current="currentIndex" @change="swiperChange">
			<swiper-item v-for="item in classList" :key="item._id">
				<image :src="item.picurl.url" mode="aspectFill" @click="maskChange"></image>
			</swiper-item>
		</swiper>
		<!-- 遮罩层 -->
		<view class="mask" v-if="maskState">
			<view class="goback" :style="{top:getStatusBarHeight() + 'px'}" @click="goBack">
				<uni-icons type="back" color="#fff" size="20"></uni-icons>
			</view>
			<view class="count">
				{{currentIndex + 1}} / {{classList.length}}
			</view>
			<view class="time">
				<uni-dateformat :date="new Date()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="new Date()" format="MM月dd日"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="box" @click="addLike">
					<uni-icons type="heart" size="30" v-if="!currentInfo.isHearted"></uni-icons>
					<uni-icons type="heart-filled" size="30" color="red" v-else></uni-icons>
					<view class="text">收藏</view>
				</view>
				<view class="box" @click="clickScore">
					<uni-icons type="star" size="30"></uni-icons>
					<view class="text">{{currentInfo.score}}分</view>
				</view>
				<view class="box" @click="download">
					<uni-icons type="download" size="30"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>
		<!-- 评分信息弹窗 -->
		<uni-popup ref="scorepopup" :is-mask-click="false">
			<view class="scorepopup">
				<!-- 弹窗头部 -->
				<view class="popheader">
					<view class="title">{{isScore ? '评分过了~' : '壁纸评分'}}</view>
					<view class="close" @click="clickScoreClose">
						<uni-icons type="closeempty" size="18" color="#999"></uni-icons>
					</view>
				</view>
				<!-- 弹窗内容 -->
				<view class="content">
					<uni-rate v-model="userScore" allowHalf :disabled="isScore" disabled-color="#ffca3e" />
					<text class="text">{{userScore}}分</text>
				</view>
				<!-- 弹窗底部 -->
				<view class="footer">
					<button :disabled="!userScore || isScore" type="default" size="mini" @click="submit"
						plain>确认评分</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref
	} from 'vue';
	import {
		getStatusBarHeight
	} from '@/utils/system.js';
	import {
		onLoad,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app';

	const maskState = ref(false)
	const currentId = ref(null);
	const scorepopup = ref(null);
	const isScore = ref(false);
	const userScore = ref(0);
	const currentIndex = ref([0]);
	const currentInfo = ref(null);
	const classList = ref([])
	const readImg = ref([]);
	const downloadedWallpapers = ref([]);
	const scoredList = ref([])
	const isHearted = ref(false)

	// 获取缓存
	const storgClassList = uni.getStorageSync("storgClassList") || [];

	classList.value = storgClassList.map(item => {
		return {
			...item,
			isHearted: false // 初始化每个壁纸的收藏状态
		}
	});
	//遮罩状态
	const maskChange = function() {
		maskState.value = !maskState.value;
	}
	onLoad(async (e) => {
		currentId.value = e.id;
		currentIndex.value = classList.value.findIndex(item => item._id == currentId.value);
		currentInfo.value = classList.value[currentIndex.value];

		// 检查评分状态
		const scoredList = uni.getStorageSync("scoreList") || [];
		isScore.value = scoredList.some(item => item._id === currentInfo.value._id); // 检查是否已评分
		userScore.value = isScore.value ? currentInfo.value.score : 0; // 如果已评分，显示当前评分

		// 检查收藏状态
		const likedList = uni.getStorageSync("likedList") || [];
		currentInfo.value.isHearted = likedList.some(item => item._id === currentInfo.value._id); // 检查是否已收藏

		readImgFun();
	});

	const swiperChange = (e) => {
		currentIndex.value = e.detail.current;
		currentInfo.value = classList.value[currentIndex.value];
		readImgFun();
	}

	//实现图片懒加载
	function readImgFun() {
		readImg.value.push(
			currentIndex.value <= 0 ? classList.value.length - 1 : currentIndex.value - 1,
			currentIndex.value,
			currentIndex.value >= classList.value.length - 1 ? 0 : currentIndex.value + 1
		)
		readImg.value = [...new Set(readImg.value)]; //去重
	}
	//返回上一页
	const goBack = function() {
		uni.navigateBack({
			success: () => {

			},
			fail: (err) => {
				uni.reLaunch({
					url: "/pages/index/index"
				})
			}
		})
	}

	// 收藏
	const addLike = () => {
		// 切换当前壁纸的收藏状态
		currentInfo.value.isHearted = !currentInfo.value.isHearted;

		// 获取当前收藏列表
		const likedList = uni.getStorageSync("likedList") || [];

		if (currentInfo.value.isHearted) {
			// 如果当前是收藏状态，检查是否已存在
			const exists = likedList.some(item => item._id === currentInfo.value._id);
			if (!exists) {
				likedList.push(currentInfo.value); // 添加到收藏列表
				uni.showToast({
					title: "已成功收藏",
					icon: 'none'
				});
			}
		} else {
			// 如果当前是取消收藏状态，从收藏列表中移除
			const index = likedList.findIndex(item => item._id === currentInfo.value._id);
			if (index !== -1) {
				likedList.splice(index, 1); // 从收藏列表中移除
				uni.showToast({
					title: "已取消收藏",
					icon: 'none'
				});
			}
		}

		// 存储更新后的收藏列表
		uni.setStorageSync("likedList", likedList);
	}

	// 评分弹窗
	const clickScore = () => {
		if (isScore.value) {
			uni.showToast({
				title: "您已评分，无法再次评分",
				icon: 'none'
			});
			return; // 如果已评分，直接返回
		}
		scorepopup.value.open();
	}

	// 关闭评分弹窗
	const clickScoreClose = function() {
		scorepopup.value.close();
	}


	// 提交评分
	const submit = () => {
		if (isScore.value) {
			uni.showToast({
				title: "您已评分，无法再次评分",
				icon: 'none'
			});
			return; // 如果已评分，直接返回
		}
		uni.showToast({
			title: "加载中...",
			icon: 'none'
		});

		// 更新当前壁纸评分
		classList.value[currentIndex.value].score = userScore.value;

		// 更新评分列表
		const scoredList = uni.getStorageSync("scoreList") || [];
		// 确保 scoredList 是一个数组
		if (!Array.isArray(scoredList)) {
			console.error("评分列表不是一个数组，重置为一个空数组");
			scoredList = [];
		}
		const existingIndex = scoredList.findIndex(item => item._id === classList.value[currentIndex.value]._id);
		if (existingIndex === -1) {
			// 如果没有评分，新增评分
			scoredList.push({
				...classList.value[currentIndex.value],
				score: userScore.value
			});
		} else {
			// 如果已有评分，更新评分
			scoredList[existingIndex].score = userScore.value;
		}

		// 存储更新后的评分列表
		uni.setStorageSync("scoreList", scoredList);
		uni.showToast({
			title: "评分成功",
			icon: 'none'
		});
		isScore.value = true; // 更新评分状态
		clickScoreClose();
	}

	// 壁纸下载
	const download = () => {
		try {
			uni.showLoading({
				title: "下载中",
				mask: true
			});
			let res = {
				id: currentInfo.value._id,
				path: currentInfo.value.picurl.url,
			};
			console.log(res);
			uni.getImageInfo({
				src: currentInfo.value.picurl.url,
				success: (res) => {
					uni.saveImageToPhotosAlbum({
						filePath: res.path,
						success: (res) => {
							uni.showToast({
								title: "保存成功",
								icon: 'none'
							});
							// 获取当前下载列表
							downloadedWallpapers.value = uni.getStorageSync("downLoadList") ||
								[];

							// 检查当前壁纸是否已存在于下载列表中
							const exists = downloadedWallpapers.value.some(item => item._id ===
								currentInfo.value._id);
							if (!exists) {
								downloadedWallpapers.value.push(currentInfo.value); // 仅在不存在时添加
							}

							// 存储更新后的下载列表
							uni.setStorageSync("downLoadList", downloadedWallpapers.value);
						},
						fail: err => {
							// ... existing error handling code ...
						},
						complete: () => {
							uni.hideLoading();
						}
					});
				}
			});
		} catch {
			uni.hideLoading();
		}
	}
	//分享给好友
	onShareAppMessage(() => {
		return {
			title: "噜啦壁纸",
			path: "/pages/detail/detail?id=" + id
		}
	})

	//分享到朋友圈
	onShareTimeline(() => {
		return {
			title: "噜啦壁纸"
		}
	})
</script>

<style lang="scss" scoped>
	.layout {
		width: 100%;
		height: 100vh;
		position: relative;

		swiper {
			width: 100%;
			height: 100%;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.mask {

			//紧邻mask的子元素的view的通用样式
			&>view {
				position: absolute;
				left: 0;
				right: 0;
				color: #fff;
				margin: auto;
				width: fit-content; //自适应

			}

			.goback {
				width: 38px;
				height: 38px;
				background: rgba(0, 0, 0, 0.5);
				left: 30rpx;
				margin-left: 0;
				border-radius: 100px;
				top: 0;
				backdrop-filter: blur(10rpx);
				border: 1rpx solid rgba(255, 255, 255, 0.3);
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.count {
				top: 10vh;
				background: rgba(0, 0, 0, 0.3);
				font-size: 28rpx;
				border-radius: 40rpx;
				padding: 8rpx 28rpx;
				backdrop-filter: blur(10rpx); //阴影
			}

			.time {
				font-size: 140rpx;
				top: calc(10vh + 80rpx);
				font-weight: 100;
				line-height: lem; //去掉默认行高
				text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
			}

			.date {
				font-size: 34rpx;
				top: calc(10vh + 230rpx);
				text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);
			}

			.footer {
				background: rgba(255, 255, 255, 0.8);
				bottom: 10vh;
				width: 65vw;
				height: 120rpx;
				border-radius: 120rpx;
				color: #000;
				display: flex;
				justify-content: space-around; //平均分配
				align-items: center;
				box-shadow: 0 2rpx rgba(0, 0, 0, 0.1);
				backdrop-filter: blur(20rpx);

				.box {
					display: flex;
					justify-content: center;
					align-items: center;
					flex-direction: column;
					padding: 2rpx 12rpx;

					.text {
						font-size: 26rpx;
					}
				}
			}
		}

		.popheader {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.title {
				color: black;
				font-size: 26rpx;
			}

			.close {
				padding: 6rpx;
			}
		}

		.scorepopup {
			background: #fff;
			padding: 30rpx;
			width: 70vw;
			border-radius: 30rpx;

			.content {
				padding: 30rpx 0;
				display: flex;
				justify-content: center;
				align-items: center;

				.text {
					color: #ffca3e;
					width: 80rpx;
					padding-left: 10rpx;
					line-height: 1em;
					text-align: right;
				}
			}

			.footer {
				padding: 10rpx 0;
				display: flex;
				justify-content: center;
				align-items: center;
			}
		}
	}
</style>